import is.glif.fenius.ws.draft.gen.DraftFeniusService;
import is.glif.fenius.ws.draft.gen.Draft;

import is.glif.fenius.ws.draft.gen.ReservationParams;
import is.glif.fenius.ws.draft.gen.EndpointPair;
import is.glif.fenius.ws.draft.gen.ExplicitRoute;
import is.glif.fenius.ws.draft.gen.EndpointParams;
import is.glif.fenius.ws.draft.gen.CommonParams;
import is.glif.fenius.ws.draft.gen.DomainParams;
import is.glif.fenius.ws.draft.gen.Status;
import is.glif.fenius.ws.draft.gen.TimeParams;

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.namespace.QName;

import java.util.List;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.GregorianCalendar;
import java.util.Enumeration;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FeniusDraftRrm extends HttpServlet {
    static public final long serialVersionUID = 01010101L;
    static public int GROUP_ID_POSOTION = 7;
    static public DatatypeFactory df = null;

    static {
	try {
	    df = DatatypeFactory.newInstance();
	} catch (javax.xml.datatype.DatatypeConfigurationException e) {
	    e.printStackTrace();
	}
    }
	
    public FeniusDraftRrm() 
    {
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
	System.err.println("=========== doGet rrm start now\n");

	String s = toXML();
	response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
        out.println(s);
	System.err.println("=========== doGet rrm end \n");

    }

    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }

    public String toXML()
    {
	String s = 
	    "<?xml version=\"1.0\"?>\n" +
	    "<reservationIDMaps xmlns=\"http://glambda/schema/2006/07/demo\"\n" +
	    "  xmlns:demo=\"http://glambda/schema/2006/07/demo\"\n" +
	    "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
	    "  xsi:schemaLocation=\"http://glambda/schema/2006/07/demo demo.xsd\">\n" +
	    "<reservationIDMap sched=\"AIST-GRS\">\n\n";

	Calendar c = Calendar.getInstance();
	c.setTime(new Date());
	c.set(Calendar.MILLISECOND, 0);

	for(Enumeration de = FeniusDraftList.dlists.keys(); de.hasMoreElements();){
	    String domain = (String) de.nextElement();
	    Hashtable<String, ReservationParams> lists = FeniusDraftList.dlists.get(domain);
	    if (lists == null) continue;

	    for(Enumeration e = lists.elements(); e.hasMoreElements();){
		ReservationParams p = (ReservationParams) e.nextElement();

		if (p == null) continue;

		String id = p.getReservationId();
		String ap = p.getEndpoints().getA();
		ap = FeniusDraftCreate.endpoint2alias.get(ap);
		String zp = p.getEndpoints().getZ();
		zp = FeniusDraftCreate.endpoint2alias.get(zp);
		String st = mapStatus(p.getEndtoendParams().getStatus());
		String bw = "" + p.getEndtoendParams().getBandwidth() * 1000;
		XMLGregorianCalendar sgc = 
		    p.getEndtoendParams().getTimeParams().getScheduledStartTime();
		Long smsec = sgc.toGregorianCalendar().getTimeInMillis();
		GregorianCalendar sgc2 = 
		    (GregorianCalendar) GregorianCalendar.getInstance();
		sgc2.setTime(new Date(smsec));
		sgc = df.newXMLGregorianCalendar(sgc2);

		String stime = sgc.toString();
		stime = stime.substring(0, 19) + "Z";

		XMLGregorianCalendar egc = 
		    p.getEndtoendParams().getTimeParams().getScheduledEndTime();
		Long emsec = egc.toGregorianCalendar().getTimeInMillis();
		GregorianCalendar egc2 = 
		    (GregorianCalendar) GregorianCalendar.getInstance();
		egc2.setTime(new Date(emsec));
		egc = df.newXMLGregorianCalendar(egc2);

		String etime = egc.toString();
		etime = etime.substring(0, 19) + "Z";
		
		Calendar ec = Calendar.getInstance();
		ec.setTime(new Date(emsec));
		ec.add(Calendar.MINUTE, FeniusDraftList.DISPLAY_TIME_MINUTE);
		if (c.after(ec)) continue;

		String setid = id.substring(0, GROUP_ID_POSOTION);

		s += "  <resourceSet id=\"" + setid + "\" distinguishedName=\"\">\n";
		s += "    <networkResource APoint=\"" + ap + "\" ZPoint=\"" + zp + "\">\n";
		s += "      <path name=\"nrm0-factoryurl\" reservationID=\"" + id + "\">\n";
		s += "        <startTime value=\"" + stime + "\"/>\n";
		s += "        <endTime value=\"" + etime + "\"/>\n";
		s += "        <reservationStatus value=\"" + st + "\"/>\n";
		s += "        <aPoint value=\"" + ap + "\"/>\n";
		s += "        <zPoint value=\"" + zp + "\"/>\n";
		// s += "         <bandwidth value=\"" + bw + "\"/>\n";
		s += "         <bandwidth value=\"" + Long.parseLong(bw) * 5 + "\"/>\n";
		s += "      </path>\n";
		s += "    </networkResource>\n";
		s += "  </resourceSet>\n\n";
	    }
	}

	s += "</reservationIDMap>\n";
	s += "</reservationIDMaps>\n";
	System.err.println("reply to RRM:" + s);

	return s;
    }

    public String mapStatus(Status s) 
    {
	String r = null;

	if (Status.REQUESTING == s) r = "Prepeared";
	else if (Status.RESERVED == s) r = "Reserved";
	else if (Status.INSETUP == s) r = "Reserved";
	else if (Status.ACTIVE == s) r = "Activated";
	else if (Status.INTEARDOWN == s) r = "Released";
	else if (Status.FINISHED == s) r = "Released";
	else if (Status.CANCELLED == s) r =  "Released";
	else if (Status.FAILED == s) r = "Error";
	else r = "Unknown";

	// if (debug) System.err.println("Status=" + s.toString() + ", return=" + r);
	return r;
    }

    public static void main(String[] args) {
	FeniusDraftRrm fdr = new FeniusDraftRrm();

	System.err.println(fdr.toXML());
	try {
	    Thread.sleep(10000L);
	} catch (Exception ex) {}

	System.err.println(fdr.toXML());
    }
}